package com.aks.server.service.impl;

import com.aks.server.domain.request.param.ActivityParam;
import com.aks.server.domain.request.param.TaskParam;
import com.aks.server.domain.response.em.ResultEnum;
import com.aks.server.en.ActivityStatusEnum;
import com.aks.server.entity.ActivityEntity;
import com.aks.server.entity.TaskEntity;
import com.aks.server.domain.response.ActivityVO;
import com.aks.server.domain.response.ResponseResult;
import com.aks.server.service.ActivityPriceCalculator;
import com.aks.server.service.ActivityService;
import com.aks.server.service.CoachService;
import com.aks.server.service.TaskService;
import com.aks.server.mapper.TaskMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CoachServiceImpl extends BaseServiceImpl implements CoachService {
    @Autowired
    private ActivityService activityService;

    @Autowired
    private TaskService taskService;

    @Resource
    private TaskMapper taskMapper;

    @Autowired
    private ActivityPriceCalculator activityPriceCalculator;

    @Override
    public ResponseResult<?> getCoachActivities(ActivityParam activityParam) {

        // 获取教练的活动列表
        List<ActivityEntity> activities = activityService.getActivitiesByCoachId(activityParam.getCoachId());

//        // 提取所有活动的ID
//        List<Long> activityIds = activities.stream()
//                .map(ActivityEntity::getId)
//                .collect(Collectors.toList());
//
//        // 获取所有活动的任务列表
//        List<TaskEntity> allTasks = taskService.getTasksByActivityList(activityIds);
//
//        // 按活动ID分组任务
//        Map<Long, List<TaskEntity>> tasksByActivityId = allTasks.stream()
//                .collect(Collectors.groupingBy(TaskEntity::getActivityId));
//
//        // 转换为ActivityVO列表
//        List<ActivityVO> activityList = activities.stream().map(activity -> {
//            ActivityVO activityVO = new ActivityVO();
//            // 设置活动基本信息
//            activityVO.setId(activity.getId());
//            activityVO.setActivityName(activity.getActivityName());
//            activityVO.setActivityDesc(activity.getActivityDesc());
//            activityVO.setActivityDays(activity.getActivityDays());
//            activityVO.setImagePath(activity.getImagePath());
//            activityVO.setActivityTheme(activity.getActivityTheme());
//            activityVO.setTeamCount(activity.getTeamCount());
//            activityVO.setTeamSize(activity.getTeamSize());
//            activityVO.setDailyStartTime(activity.getDailyStartTime());
//            activityVO.setDailyEndTime(activity.getDailyEndTime());
//            activityVO.setTotalPeople(activity.getTotalPeople());
//            activityVO.setCoachId(activity.getCoachId());
//            activityVO.setActivityStatus(activity.getActivityStatus());
//            activityVO.setCreateTime(activity.getCreateTime());
//            activityVO.setUpdateTime(activity.getUpdateTime());
//
//            // 设置该活动的任务列表
//            List<TaskEntity> activityTasks = tasksByActivityId.getOrDefault(activity.getId(), new ArrayList<>());
//            List<TaskVO> taskVOs = activityTasks.stream().map(task -> {
//                TaskVO taskVO = new TaskVO();
//                taskVO.setId(task.getId());
//                taskVO.setActivityId(task.getActivityId());
//                taskVO.setTaskName(task.getTaskName());
//                taskVO.setTaskDesc(task.getTaskDesc());
//                taskVO.setTaskLevel(task.getTaskLevel());
//                taskVO.setTaskType(task.getTaskType());
//                taskVO.setCreateTime(task.getCreateTime());
//                taskVO.setUpdateTime(task.getUpdateTime());
//                return taskVO;
//            }).collect(Collectors.toList());
//            activityVO.setTasks(taskVOs);
//            return activityVO;
//        }).collect(Collectors.toList());
        
        return ResponseResult.success(ResultEnum.RETURN_SUCCESS, activities);
    }

    @Override
    public ResponseResult<?> getActivitityTask(TaskParam taskParam) {
        List<TaskEntity> taskList= taskService.listTasks(taskParam.getActivityId());
        return ResponseResult.success(ResultEnum.RETURN_SUCCESS, taskList);
    }

    @Override
    public ResponseResult<?> dealcalcAmount(ActivityParam activityParam) {
        //定义返回集合
        ActivityVO vo=new ActivityVO();
        // 1. 将 ActivityParam 转换为 ActivityEntity
        ActivityEntity activityEntity = new ActivityEntity();
        BeanUtils.copyProperties(activityParam, activityEntity);
        // 2. 计算价格
        activityEntity.setPrice(activityPriceCalculator.calculatePrice(activityParam));
        // 3. 初始化状态0-待支付
        activityEntity.setActivityStatus(ActivityStatusEnum.PENDING_PAYMENT.getCode());
        // 4. 保存
        activityService.createActivity(activityEntity);
        // 5. 获取保存后的活动ID
        Long activityId = activityEntity.getId();
        // 6. 批量保存任务列表
        if (activityParam.getTasks() != null && !activityParam.getTasks().isEmpty()) {
            List<TaskEntity> taskEntities = activityParam.getTasks().stream()
                .map(taskParam -> {
                    TaskEntity taskEntity = new TaskEntity();
                    BeanUtils.copyProperties(taskParam, taskEntity);
                    taskEntity.setActivityId(activityId);
                    return taskEntity;
                })
                .collect(Collectors.toList());
            // 使用 MyBatis-Plus 的批量保存功能
            taskEntities.forEach(taskMapper::insert);
        }
        BeanUtils.copyProperties(activityEntity, vo);
        return ResponseResult.success(ResultEnum.RETURN_SUCCESS, vo);
    }

    @Override
    public ResponseResult<?> update(ActivityParam activityParam) {
        // 1. 获取当前活动信息
        ResponseResult<?> result = activityService.getActivityById(activityParam.getId());
        ActivityEntity existingActivity = (ActivityEntity) result.getData();
        if (existingActivity == null) {
            return ResponseResult.fail(ResultEnum.RETURN_FAIL.getCode(), "活动不存在", null);
        }

        // 2. 根据活动状态进行不同的处理
        String currentStatus = existingActivity.getActivityStatus();
        
        // 2.1 如果状态为已完成，不允许任何修改
        if (ActivityStatusEnum.COMPLETED.getCode().equals(currentStatus)) {
            return ResponseResult.fail(ResultEnum.RETURN_FAIL.getCode(), "已完成的活动不允许修改", null);
        }

        // 2.2 如果状态为已支付、已测试、已开始，只允许修改开始时间和结束时间
        if (ActivityStatusEnum.PAID.getCode().equals(currentStatus) 
            || ActivityStatusEnum.TESTED.getCode().equals(currentStatus)
            || ActivityStatusEnum.STARTED.getCode().equals(currentStatus)) {
            
            // 只更新开始时间和结束时间
            existingActivity.setDailyStartTime(activityParam.getDailyStartTime());
            existingActivity.setDailyEndTime(activityParam.getDailyEndTime());
            
            // 更新活动
            activityService.updateActivity(activityParam);
            
            // 处理任务列表 - 只允许修改现有任务，不允许添加新任务
            if (activityParam.getTasks() != null && !activityParam.getTasks().isEmpty()) {
                // 获取需要更新的任务列表
                List<TaskEntity> updateTasks = activityParam.getTasks().stream()
                    .filter(taskParam -> taskParam.getId() != null)
                    .map(taskParam -> {
                        TaskEntity taskEntity = new TaskEntity();
                        BeanUtils.copyProperties(taskParam, taskEntity);
                        return taskEntity;
                    })
                    .collect(Collectors.toList());
                
                // 批量更新任务
                if (!updateTasks.isEmpty()) {
                    updateTasks.forEach(taskMapper::updateById);
                }
            }
            
            return ResponseResult.success(ResultEnum.RETURN_SUCCESS, existingActivity);
        }

        // 2.3 如果状态为待支付，允许修改任何内容，需要重新计算费用
        if (ActivityStatusEnum.PENDING_PAYMENT.getCode().equals(currentStatus)) {
            // 更新活动基本信息
            ActivityEntity activityEntity = new ActivityEntity();
            BeanUtils.copyProperties(activityParam, activityEntity);
            
            // 重新计算价格
            activityEntity.setPrice(activityPriceCalculator.calculatePrice(activityParam));
            
            // 更新活动
            activityService.updateActivity(activityParam);
            
            // 处理任务列表
            if (activityParam.getTasks() != null) {
                // 获取现有任务列表
                List<TaskEntity> existingTasks = taskService.listTasks(activityParam.getId());
                
                // 分离需要更新和新增的任务
                List<TaskEntity> updateTasks = activityParam.getTasks().stream()
                    .filter(taskParam -> taskParam.getId() != null)
                    .map(taskParam -> {
                        TaskEntity taskEntity = new TaskEntity();
                        BeanUtils.copyProperties(taskParam, taskEntity);
                        return taskEntity;
                    })
                    .collect(Collectors.toList());
                
                List<TaskEntity> newTasks = activityParam.getTasks().stream()
                    .filter(taskParam -> taskParam.getId() == null)
                    .map(taskParam -> {
                        TaskEntity taskEntity = new TaskEntity();
                        BeanUtils.copyProperties(taskParam, taskEntity);
                        taskEntity.setActivityId(activityParam.getId());
                        return taskEntity;
                    })
                    .collect(Collectors.toList());
                
                // 批量更新现有任务
                if (!updateTasks.isEmpty()) {
                    updateTasks.forEach(taskMapper::updateById);
                }
                
                // 批量插入新任务
                if (!newTasks.isEmpty()) {
                    newTasks.forEach(taskMapper::insert);
                }
                
                // 删除不在新任务列表中的任务
                List<Long> newTaskIds = activityParam.getTasks().stream()
                    .map(TaskParam::getId)
                    .filter(id -> id != null)
                    .collect(Collectors.toList());
                
                existingTasks.stream()
                    .filter(task -> !newTaskIds.contains(task.getId()))
                    .forEach(task -> taskMapper.deleteById(task.getId()));
            }
            
            return ResponseResult.success(ResultEnum.RETURN_SUCCESS, activityEntity);
        }

        return ResponseResult.fail(ResultEnum.RETURN_FAIL.getCode(), "无效的活动状态", null);
    }
} 